package com.github.bridge.init;

import cn.hutool.extra.spring.SpringUtil;
import com.github.bridge.util.Const;
import com.timevale.esign.paas.tech.bean.result.Result;
import com.timevale.esign.paas.tech.client.ServiceClientManager;
import com.timevale.tech.sdk.bean.HttpConnectionConfig;
import com.timevale.tech.sdk.bean.ProjectConfig;
import com.timevale.tech.sdk.bean.SignatureConfig;
import com.timevale.tech.sdk.constants.AlgorithmType;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * 服务启动后干的事
 *
 * @author zhanghui
 * @date 2024/8/16 上午9:26
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class StartupRunner implements CommandLineRunner {

    @Value("${e.sign.sdkAppId}")
    private String esginAppId;
    @Value("${e.sign.sdkAppSecret}")
    private String esginAppSecret;
    @Value("${e.sign.sdkUrl}")
    private String esginSdkUrl;


    @Override
    @SneakyThrows
    public void run(String... args) {
        initESignSDK();
        log.info("服务端启动完成");
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = SpringUtil.getApplicationContext().getEnvironment().getProperty("server.port");
        log.info("\n----------------------------------------------------------\n\t" +
                "Application is running! Access URLs:\n\t" +
                "Local: \t\thttp://localhost:" + port + "/\n\t" +
                "External: \thttp://" + ip + ":" + port + "/\n\t" +
                "Swagger文档: \thttp://" + ip + ":" + port + "/doc.html\n" +
                "----------------------------------------------------------");
    }

    public void initESignSDK() {
        // http://smlitsm.tsign.cn:8080/tgmonitor/rest/app!getAPIInfo2
        Const.E_SIGN_APP_ID = esginAppId;
        ProjectConfig projectConfig = new ProjectConfig();
        projectConfig.setProjectId(esginAppId);
        projectConfig.setProjectSecret(esginAppSecret);
        projectConfig.setItsmApiUrl(esginSdkUrl);
        SignatureConfig signatureConfig = new SignatureConfig();
        signatureConfig.setAlgorithm(AlgorithmType.HMACSHA256);
        Result result = ServiceClientManager.registClient(projectConfig, new HttpConnectionConfig(), signatureConfig);
        boolean success = result.success();
        if (success) {
            log.info("esign sdk register success");
        } else {
            throw new RuntimeException("esign sdk register fail");
        }
    }
}
